package com.intelligent.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.intelligent.pojo.CustomerManagement;
import com.intelligent.pojo.TUser;
import com.intelligent.service.CustomerManagementService;
import com.intelligent.service.TUserService;
import com.intelligent.utils.Result;
import com.intelligent.vo.CustomerPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/customer-info")
public class CustomerInfoController {

    @Autowired
    private CustomerManagementService customerManagementService;

    @Autowired
    private TUserService tUserService;

    // 分页查询
    @PostMapping("/page")
    public Result<Page<CustomerManagement>> pageList(@RequestBody CustomerPage customerPage) {
        Page<CustomerManagement> page = new Page<>(customerPage.getPageNum(), customerPage.getPageSize());
        LambdaQueryWrapper<CustomerManagement> wrapper = new LambdaQueryWrapper<>();
        if (customerPage.getCustomerName() != null) {//根据客户名称查询
            wrapper.like(CustomerManagement::getCustomerName, customerPage.getCustomerName());
        }
        if (customerPage.getUId() != null) {//
            wrapper.eq(CustomerManagement::getUId, customerPage.getUId());
        }

        if (customerPage.getStatus() != null) {//根据状态查询
            wrapper.eq(CustomerManagement::getStatus, customerPage.getStatus());
        }
        wrapper.orderByDesc(CustomerManagement::getId);//按照id字段进行降序排序
        Page<CustomerManagement> result = customerManagementService.page(page, wrapper);

        // 关联用户表获取联系人姓名
        if (result.getRecords() != null && !result.getRecords().isEmpty()) {
            // 获取所有用户ID
            List<Long> userIds = result.getRecords().stream()
                    .map(CustomerManagement::getUId)
                    .filter(uId -> uId != null)
                    .distinct()
                    .collect(Collectors.toList());

            if (!userIds.isEmpty()) {
                // 批量查询用户信息
                LambdaQueryWrapper<TUser> userWrapper = new LambdaQueryWrapper<>();
                userWrapper.in(TUser::getUserId, userIds);
                List<TUser> users = tUserService.list(userWrapper);

                // 构建用户ID到用户名的映射
                Map<Long, String> userMap = users.stream()
                        .collect(Collectors.toMap(TUser::getUserId, TUser::getRealName));

                // 设置联系人姓名
                result.getRecords().forEach(customer -> {
                    if (customer.getUId() != null) {
                        customer.setContactPersonName(userMap.get(customer.getUId()));
                    }
                });
            }
        }

        return Result.success(result);
    }


    //新建，保存
    @PostMapping
    @Transactional(rollbackFor = Exception.class)
    public Result<CustomerManagement> create(@RequestBody CustomerManagement customerManagement) {
        // 设置默认状态为启用(0)
        if (customerManagement.getStatus() == null) {
            customerManagement.setStatus(0);
        }
        // 首次保存以获取自增ID
        boolean saved = customerManagementService.save(customerManagement);
        if (!saved) {
            return Result.error("保存失败");
        }
        // 基于规则生成客户编号：KH+年份+月份+4位数自增ID
        String yearMonth = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMM"));
        String idPart = String.format("%04d", customerManagement.getId());
        String customerCode = "KH" + yearMonth + idPart;
        customerManagement.setCustomerCode(customerCode);
        // 更新记录写入客户编号
        boolean updated = customerManagementService.updateById(customerManagement);
        if (!updated) {
            return Result.error("写入客户编号失败");
        }
        return Result.success(customerManagement);
    }

    //查询详情
    @GetMapping("/{id}")
    public Result<CustomerManagement> detail(@PathVariable Integer id) {
        CustomerManagement customerManagement = customerManagementService.getById(id);
        if (customerManagement == null) {
            return Result.error("未找到数据");
        }

        // 关联用户表获取联系人姓名
        if (customerManagement.getUId() != null) {
            TUser user = tUserService.getById(customerManagement.getUId());
            if (user != null) {
                customerManagement.setContactPersonName(user.getRealName());
            }
        }
        return Result.success(customerManagement);
    }

    //更新状态
    @PutMapping("/{id}/status")
    public Result<Boolean> updateStatus(@PathVariable Integer id, @RequestParam Integer status) {
        CustomerManagement customerManagement = customerManagementService.getById(id);
        if (customerManagement == null) {
            return Result.error("未找到数据");
        }
        customerManagement.setStatus(status);
        boolean updated = customerManagementService.updateById(customerManagement);
        if (!updated) {
            return Result.error("状态更新失败");
        }
        return Result.success(true);
    }

    //获取用户列表
    @GetMapping("/users")
    public Result<List<TUser>> getUserList() {
        LambdaQueryWrapper<TUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TUser::getStatus, 1); // 只获取启用的用户
        wrapper.select(TUser::getUserId, TUser::getRealName, TUser::getUsername);
        List<TUser> users = tUserService.list(wrapper);
        return Result.success(users);
    }
}


